package net.aiion.weave.impl.ui.xhtml;

import java.io.InputStream;

import net.aiion.weave.spi.cards.CardService;
import net.aiion.weave.spi.injection.annotations.Inject;
import net.aiion.weave.spi.naming.Context;
import net.aiion.weave.spi.naming.annotations.Named;
import net.aiion.weave.spi.naming.annotations.NotScoped;
import net.aiion.weave.spi.painters.PaintBrush;
import net.aiion.weave.spi.painters.PaintContext;
import net.aiion.weave.spi.painters.annotations.Paints;
import net.aiion.weave.spi.painters.stream.xhtml.XhtmlPaintBrush;
import net.aiion.weave.spi.resources.ResourceService;
import net.aiion.weave.spi.xml.XmlSinkFactory;

@NotScoped
@Named
public class XhtmlPainter
{
    @Inject
    private Context namingContext;

    @Inject
    private CardService xspProcessor;

    @Inject
    private ResourceService resourceService;

    public XhtmlPainter() {
    }

    @Paints(Object.class)
    public PaintBrush paintInstance(final PaintContext aPainterContext) {
        final XhtmlPaintBrush xhtmlCrayon = aPainterContext.getPaintBrush(XhtmlPaintBrush.class);
        final Object namedInstance = aPainterContext.getComponent();

        final InputStream inputStream = resourceService.findResource(namedInstance, ".xhtml").openStream();
        if (inputStream == null) {
            return aPainterContext.forwardPaint();
        }

        xspProcessor.setComponent(namedInstance);
        xspProcessor.setInputStream(inputStream);
        xspProcessor.setReader(XmlSinkFactory.getInstance().createWriter(xhtmlCrayon.getOutputStream()));
        xspProcessor.addTransformer(namingContext.lookup(XhtmlStyleTransformer.class));
        xspProcessor.addTransformer(new XhtmlTransformer());
        xspProcessor.addTransformer(new XhtmlWhitespaceTransformer());
        xspProcessor.findXmlCard();

        return xhtmlCrayon;
    }
}
